<template>
  <div class="img div-video1-zdy">
    <a-upload
      name="file"
      listType="picture-card"
      :customRequest="uploadImage"
      :headers="headers"
      :data="{biz:bizPath}"
      :beforeUpload="beforeUpload"
      :disabled="type == 1 ? false : true"
      :showUploadList="false"
      :isMultiple="isMultiple"
      @change="handleChange"
      @preview="handlePreview"
      :class="!isMultiple?'imgupload':''">
        <img v-if="!isMultiple && picUrl" :src="getAvatamethodsrView()" style="height:104px;max-width:300px"/>
        <div v-else class="iconp" >
          <div v-show="type==1">
            <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">{{ text }}</div>
          </div>
          <div v-show="type==2">
            <a-icon type="loading" />
            <div class="ant-upload-text">上传中{{progress}}%</div>
          </div>
        </div>
        <!--<img v-show="fileList.length > 0 && oneFile"
             :src="fileList[fileList.length-1]+'?x-oss-process=video/snapshot,t_100000,f_jpg,w_800,h_600'"
             :style="videoHeightAuto"/>-->
        <!--<div v-if="fileList.length > 0 && oneFile" :style="videoHeightAuto ">
          <video class="video-js vjs-default-skin" id="videoLoad" :style="videoHeightAuto" controls preload="none" width="100" height="100"
                 :poster="fileList[fileList.length-1]+'?x-oss-process=video/snapshot,t_100000,f_jpg,w_800,h_600'"
                 data-setup="{}">
            <source :src="fileList[fileList.length-1]" />
          </video>
        </div>-->
        <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel()">
          <!--<video class="video-js vjs-default-skin" style="float: left; z-index: 999" controls preload="none" width="100" height="100"
                 :poster="video+'?x-oss-process=video/snapshot,t_100000,f_jpg,w_800,h_600'"
                 data-setup="{}">
            <source :src="video" />
          </video>-->
        </a-modal>
    </a-upload>
    <div class="div-video-zdy" v-show="!oneFile">
      <div v-if="fileList.length > 0" v-for="(video, index) in fileList" style="float: left;margin-right: 10px; ">
        <video class="video-js vjs-default-skin" style="float: left; z-index: 999" controls preload="none" width="100" height="100"
               :poster="video+'?x-oss-process=video/snapshot,t_100000,f_jpg,w_800,h_600'"
               data-setup="{}">
          <source :src="video" />
        </video>
        <a-icon type="delete" style="font-size: 20px;" @click="del(index)"/>
      </div>
    </div>
  </div>
</template>

<script>
  import Vue from 'vue'
  import {ACCESS_TOKEN} from "@/store/mutation-types"
  import {getFileAccessHttpUrl} from '@/api/manage'

  const uidGenerator=()=>{
    return '-'+parseInt(Math.random()*10000+1,10);
  }
  const getFileName=(path)=>{
    if(path.lastIndexOf("\\")>=0){
      let reg=new RegExp("\\\\","g");
      path = path.replace(reg,"/");
    }
    return path.substring(path.lastIndexOf("/")+1);
  }
  export default {
    name: 'JVideoUpload',
    data(){
      return {
        uploadAction:window._CONFIG['domianURL']+"/sys/common/upload",
        uploadLoading:false,
        picUrl:false,
        headers:{},
        heightZdy: 10,
        fileList: [],
        videoHeightAuto: 'width:100%;height:-webkit-fill-available;float: left; z-index: 999',
        previewImage:"",
        previewVisible: false,
        type: 1,
        progress: 0,
      }
    },
    props:{
      text:{
        type:String,
        required:false,
        default:"上传"
      },
      oneFile:{
        type:Boolean,
        required:false,
        default:false
      },
      /*这个属性用于控制文件上传的业务路径*/
      bizPath:{
        type:String,
        required:false,
        default:"temp"
      },
      value:{
        type:[String,Array],
        required:false
      },
      disabled:{
        type:Boolean,
        required: false,
        default: true
      },
      initUrl:{
        type:String,
        required: false,
        default: ''
      },
      disabledFileList:{
        type:Number,
        required: false,
        default: -1
      },
      widthAuthIndex: {
        type:Number,
        required:false,
        default: -1
      },
      isMultiple:{
        type:Boolean,
        required:false,
        default: false
      }
    },
    watch:{
      value(val){
        if (val instanceof Array) {
          this.initFileList(val.join(','))
        } else {
          this.initFileList(val)
        }
        if(!val || val.length==0){
          this.picUrl = false;
        }
      }
    },
    created(){
      var that = this
      if(this.widthAuthIndex >= 0){
        Vue.nextTick(function () {
          document.getElementsByClassName("ant-upload-select-picture-card")[that.widthAuthIndex ? 0 : that.widthAuthIndex].style.maxHeight= '500px'
          document.getElementsByClassName("ant-upload-select-picture-card")[that.widthAuthIndex ? 0 : that.widthAuthIndex].style.width='100%'
          var heightSplit = document.getElementsByClassName("ant-upload-select-picture-card")[that.widthAuthIndex ? 0 : that.widthAuthIndex].offsetWidth / 3
          document.getElementsByClassName("ant-upload-select-picture-card")[that.widthAuthIndex ? 0 : that.widthAuthIndex].style.height= heightSplit + 'px'
          that.videoHeightAuto += 'width:100%;height:'+heightSplit + 'px'
          that.heightZdy = heightSplit
        })
      }
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token":token}
      //初始化视频地址
    },
    methods:{
      initFileList(paths){
        if(!paths || paths.length==0){
          this.fileList = [];
          return;
        }else {
          this.fileList = paths.split(',')
        }
      },
      del: function(index){
        this.fileList.splice(index, 1)
        this.handlePathChange()
        //this.$message.success('删除成功');
      },
      uploadImage: function(file){
        if(this.oneFile) {
          this.del(0)
        }
        var self = this
        const OSS = require('ali-oss')
        const client = new OSS({
          bucket: 'gunku-test',
          // region以杭州为例（oss-cn-hangzhou），其他region按实际情况填写。
          region: 'oss-cn-beijing',
          // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
          accessKeyId: 'LTAI4GKpuVvTRkuc1dzcw4GL',
          accessKeySecret: 'RH9jVJwez60HnGjVAWMMJ8UeXJBSpG',
          timeout: 3600,
        });

        let checkpoint
        let intCount = 0
        let total = Math.ceil(file.file.size / 1048576)
        async function put () {
          var uuid = require('node-uuid');
          var uid = uuid.v1();
          var filename = "video/"+self.formatDateDay()+'/'+uid+'.mp4'
          self.type = 2
          for (let i = 0; i < 10; i++) {
            try {
              const result = await client.multipartUpload(filename, file.file, { checkpoint,
                async progress(percentage, cpt) {
                  checkpoint = cpt
                  self.progress = Math.ceil((intCount / total).toFixed(2) * 100)
                  intCount = intCount + 1
                },
              });
              if(result.res.status == 200) {
                self.$message.success('上传成功');
                self.type = 1
                self.progress = 0
                self.fileList.push(result.res.requestUrls[0].split("?")[0])
                self.handlePathChange()
              }else {
                self.$message.error('上传失败');
                self.type = 1
                self.progress = 0
              }
              break;
            } catch (e) {
              self.$message.warning('上传异常：' + e.message);
              self.type = 1
              self.progress = 0
            }
          }
        }

        put();
      },
      beforeUpload: function(file){
        var fileType = file.type.split('/')[0];
        if(fileType != 'video'){
          this.$message.warning('请上传视频格式文件');
          return false;
        }
      },
      handleChange(info) {
      },
      // 预览
      handlePreview (file) {
        this.previewImage = file.url || file.thumbUrl
        this.previewVisible = true
      },
      getAvatarView(){
        if(this.fileList.length>0){
          let url = this.fileList[0].url
          return getFileAccessHttpUrl(url)
        }
      },
      handlePathChange(){
        console.log(this.fileList)
        let uploadFiles = this.fileList
        let path = ''
        if(!uploadFiles || uploadFiles.length==0){
          path = ''
        }else {
          path = uploadFiles.join(",")
        }
        if(this.oneFile) {
          let documentEle = document.getElementById("videoLoad");
          if(documentEle != null) {
            documentEle.load()
          }
        }
        this.$emit('change', path);
        this.$emit('onVideoChange', this.fileList[this.fileList.length-1])
      },
      handleDelete(file){
        //如有需要新增 删除逻辑
      },
      handleCancel() {
        this.close();
        this.previewVisible = false;
      },
      close () {

      },
      formatDate() {
        let date = new Date();
        let year = date.getFullYear(); // 年
        let month = date.getMonth() + 1; // 月
        let day = date.getDate(); // 日
        let week = date.getDay(); // 星期
        let weekArr = [ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" ];
        let hour = date.getHours(); // 时
        hour = hour < 10 ? "0" + hour : hour; // 如果只有一位，则前面补零
        let minute = date.getMinutes(); // 分
        minute = minute < 10 ? "0" + minute : minute; // 如果只有一位，则前面补零
        let second = date.getSeconds(); // 秒
        second = second < 10 ? "0" + second : second; // 如果只有一位，则前面补零
        return `${year}${month}${day}${hour}${minute}${second}`
      },
      formatDateDay() {
        let date = new Date();
        let year = date.getFullYear() // 年
        let month = date.getMonth() + 1 // 月
        let day = date.getDate() // 日
        return `${year}${month}${day}`
      }
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style scoped>
  /* update--begin--autor:lvdandan-----date:20201016------for：j-image-upload图片组件单张图片详情回显空白
  * https://github.com/zhangdaiscott/jeecg-boot/issues/1810
  * https://github.com/zhangdaiscott/jeecg-boot/issues/1779
  */
  /deep/ .imgupload .ant-upload-select{display:block}
  /deep/ .imgupload .ant-upload.ant-upload-select-picture-card{ width:120px;height: 120px;}
  /deep/ .imgupload .iconp{padding:32px;}
  /* update--end--autor:lvdandan-----date:20201016------for：j-image-upload图片组件单张图片详情回显空白*/
  .div-video-width {
    width: 100%;
    height: 200px;
  }
  .video-div-height{}
</style>